// version v0.0.2
// create by ruicky
// detail url: https://github.com/ruicky/jd_sign_bot

const exec = require('child_process').execSync;
const fs = require('fs');
const rp = require('request-promise');
const download = require('download');

// 公共变量
const KEY = process.env.JD_COOKIE;
const serverJ = process.env.PUSH_KEY;
const DualKey = process.env.JD_COOKIE_2;
const dingdingWebhookUrl = process.env.DINGDING_WEBHOOK_URL;
const dingdingKeyword = process.env.DINGDING_KEYWORD;


// 调整时区
function getTimeByTimeZone(timeZone){
    var d = new Date();
        localTime = d.getTime(),
        localOffset=d.getTimezoneOffset()*60000, //获得当地时间偏移的毫秒数,这里可能是负数
            utc = localTime + localOffset, //utc即GMT时间
            offset = timeZone, //时区，北京市+8  美国华盛顿为 -5
            localSecondTime = utc + (3600000*offset);  //本地对应的毫秒数
    var date = new Date(localSecondTime).toLocaleString('chinese',{hour12:false});
    console.log("根据本地时间得知"+timeZone+"时区的时间是 " + date);
    console.log("系统默认展示时间方式是："+ d.toLocaleString('chinese',{hour12:false}));
    return date;
}
getTimeByTimeZone(8)  //设置时区为UTC+8


async function downFile () {
    // const url = 'https://cdn.jsdelivr.net/gh/NobyDa/Script@master/JD-DailyBonus/JD_DailyBonus.js'
    const url = 'https://raw.githubusercontent.com/NobyDa/Script/master/JD-DailyBonus/JD_DailyBonus.js';
    await download(url, './');
}

async function changeFile () {
   let content = await fs.readFileSync('./JD_DailyBonus.js', 'utf8')
   content = content.replace(/var Key = ''/, `var Key = '${KEY}'`);
   if (DualKey) {
    content = content.replace(/var DualKey = ''/, `var DualKey = '${DualKey}'`);
   }
   await fs.writeFileSync( './JD_DailyBonus.js', content, 'utf8')
}
async function sendNotify(title,content){
    if (dingdingWebhookUrl) {
        return sendNotifyDingding(title, content)
        
    } else if (serverJ) {
        return sendNotifyServerJ(title, content)
        
    }

    return Promise.resolve('没有设置任何推送方式')
}

// server 酱推送
async function sendNotifyServerJ (text,desp) {
  const options ={
    uri:  `https://sc.ftqq.com/${serverJ}.send`,
    form: { text, desp },
    json: true,
    method: 'POST'
  }
  return rp.post(options)
}

async function sendNotifyDingding (title, desc) {
    const options = {
        method: 'POST',
        uri: dingdingWebhookUrl,
        headers: {
            'Content-Type': 'application/json'
        },
        body: {
            'msgtype': 'text',
            'text': {'content': `[${dingdingKeyword || '未设置钉钉关键词'}]\n${desc}\n${title}`},
        },
        json: true,
    };
    return rp(options)
}

async function start() {
  if (!KEY) {
    console.log('请填写 key 后在继续')
    return
  }
  // 下载最新代码
  await downFile();
  console.log('下载代码完毕')
  // 替换变量
  await changeFile();
  console.log('替换变量完毕')
  // 执行
  await exec("node JD_DailyBonus.js >> result.txt");
  console.log('执行完毕')

    const path = "./result.txt"
    let content = ""
    if (fs.existsSync(path)) {
        content = fs.readFileSync(path, "utf8")
    }
    let t = content.match(/【签到概览】:((.|\n)*)【签到奖励】/)
    let res = t ? t[1].replace(/\n/, '') : '失败'
    let t2 = content.match(/【签到奖励】:((.|\n)*)【其他奖励】/)
    let res2 = t2 ? t2[1].replace(/\n/, '') : '总计0'

    await sendNotify("" + ` ${res2} ` + ` ${res} ` + new Date().toLocaleString('chinese',{hour12:false}), content);
    console.log('签到消息已推送')
  }

start()
